package com.hifar.test.test.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.common.QueryParamBean;
import com.hifar.constant.SystemConsts;
import com.hifar.fw.utils.lang.NumberUtils;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.model.VO.IdVO;
import com.hifar.model.VO.QueryParamsVO;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.sys.BusiResponse;
import com.hifar.sys.PageResult;
import com.hifar.sys.SystemLoginUser;
import com.hifar.sys.SystemUtil;
import com.hifar.test.collectdata.pojo.VO.ClimateCollectionData;
import com.hifar.test.collectdata.service.ICollectDataService;
import com.hifar.test.entrust.constant.TestConsts;
import com.hifar.test.entrust.pojo.HfEnvGkPiece;
import com.hifar.test.entrust.service.IHfEnvGkPieceService;
import com.hifar.test.equip.pojo.HfResEquip;
import com.hifar.test.equip.service.IHfResEquipService;
import com.hifar.test.test.pojo.HfEnvTaskTestRelation;
import com.hifar.test.test.pojo.HfEnvTest;
import com.hifar.test.test.pojo.HfEnvTestSensor;
import com.hifar.test.test.pojo.VO.*;
import com.hifar.test.test.service.IHfEnvTaskTestRelationService;
import com.hifar.test.test.service.IHfEnvTestSensorService;
import com.hifar.test.test.service.IHfEnvTestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhuWeiWei
 * @description 试验单
 * @date 2025/5/29 14:29
 */
@RestController
@RequestMapping("/api/busi/test/envTest")
@Api(tags = "试验单")
public class HfEnvTestController {

    @Autowired
    private IHfEnvTestService testService;

    @Autowired
    private IHfResEquipService resEquipService;

    @Autowired
    private ICollectDataService collectDataService;

    @Autowired
    private IHfEnvGkPieceService gkPieceService;

    @Autowired
    private IBaseOssFilesService ossFilesService;
    @Autowired
    private IHfEnvTaskTestRelationService taskTestRelationService;

    @Autowired
    private IHfEnvTestSensorService testSensorService;


    @ApiOperation("设备列表查询")
    @GetMapping("/testEquipList")
    public BusiResponse testEquipList(@RequestParam(value = "keyWord", required = false) String keyWord,
                                       @RequestParam(value = "equipTypeCode", required = false) String equipTypeCode) {
        QueryWrapper<HfResEquip> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(StringUtils.isNotBlank(equipTypeCode), HfResEquip::getEquipTypeCode, equipTypeCode)
                .orderByAsc(HfResEquip::getRowSort);
        List<HfResEquip> equipList = resEquipService.list(queryWrapper);

        QueryWrapper<HfEnvTest> testNotStartQueryWrapper = Wrappers.query();
        testNotStartQueryWrapper.select("count(1) count", "equip_id");
        testNotStartQueryWrapper.in("status", TestConsts.TEST_STATUS_WKS, TestConsts.TEST_STATUS_ING);
        testNotStartQueryWrapper.like(StringUtils.isNotBlank(keyWord), "equip_name", keyWord);
        testNotStartQueryWrapper.groupBy("equip_id");
        List<Map<String, Object>> testNotStartEquipGroupList = testService.listMaps(testNotStartQueryWrapper);
        Map<String, Integer> testNotStartNumMap = testNotStartEquipGroupList.stream()
                .collect(Collectors.toMap(
                        item -> StringUtils.trimNull(item.get("equipId")),
                        item -> NumberUtils.parseInt(item.get("count")),
                        Integer::sum
                ));


        QueryWrapper<HfEnvTest> testAllQueryWrapper = Wrappers.query();
        testAllQueryWrapper.select("count(1) count", "equip_id");
        testAllQueryWrapper.in("status", TestConsts.TEST_STATUS_WKS, TestConsts.TEST_STATUS_ING, TestConsts.TEST_STATUS_RUN);
        testAllQueryWrapper.groupBy("equip_id");
        List<Map<String, Object>> testEquipGroupList = testService.listMaps(testAllQueryWrapper);
        Map<String, Integer> testNumMap = testEquipGroupList.stream()
                .collect(Collectors.toMap(
                        item -> StringUtils.trimNull(item.get("equipId")),
                        item -> NumberUtils.parseInt(item.get("count")),
                        Integer::sum
                ));
        List<HfEnvTestEquipVO> equipVOList = equipList.stream()
                .map(item -> {
                    HfEnvTestEquipVO hfEnvTestEquipVO = new HfEnvTestEquipVO();
                    BeanUtils.copyProperties(item, hfEnvTestEquipVO);
                    String equipId = item.getId();
                    Integer notStartTestNum = testNotStartNumMap.getOrDefault(equipId, 0);
                    Integer testNum = testNumMap.getOrDefault(equipId, 0);
                    hfEnvTestEquipVO.setTestNum(testNum);
                    hfEnvTestEquipVO.setNotStartTestNum(notStartTestNum);
                    return hfEnvTestEquipVO;
                }).collect(Collectors.toList());
        return BusiResponse.OK(equipVOList);
    }



    @PostMapping("/listPage")
    @ApiOperation(value = "任务执行功能:试验列表查询")
    public BusiResponse listPage(@RequestBody TestQueryParamVO testQueryParamVO) {
        String equipId = testQueryParamVO.getEquipId();
        String equipTypeCode = testQueryParamVO.getEquipTypeCode();
        QueryParamBean<HfEnvTestVO> queryParamBean = new QueryParamBean<>(testQueryParamVO);
        queryParamBean.addColumns(HfEnvTest.class, "t");
        queryParamBean.addField("entrustCode", "ge");
        QueryWrapper<HfEnvTestVO> queryWrapper = queryParamBean.getQueryWrapper();
        Page<HfEnvTestVO> page = queryParamBean.getPage();
        queryWrapper.in("t.secret_level", SystemLoginUser.dataSecretSet);
        if (StringUtils.isNotBlank(equipId)) {
            queryWrapper.eq("t.equip_id", equipId);
        }
        // 根据设备类型过滤：1-气候，2-力学
        if (StringUtils.isNotBlank(equipTypeCode)) {
            queryWrapper.eq("e.equip_type_code", equipTypeCode);
        }
        String finishFlag = testQueryParamVO.getFinishFlag();
        String forceEndFlag = testQueryParamVO.getForceEndFlag();
        String revokeFlag = testQueryParamVO.getRevokeFlag();
        if (Objects.equals(SystemConsts.NO, finishFlag)) {
            queryWrapper.ne("t.status", TestConsts.TEST_STATUS_FINISH);
        }
        if (Objects.equals(SystemConsts.NO, forceEndFlag)) {
            queryWrapper.ne("t.status", TestConsts.TEST_STATUS_STOP);
        }
        if (Objects.equals(SystemConsts.NO, revokeFlag)) {
            queryWrapper.ne("t.status", TestConsts.TEST_STATUS_REVOKE);
        }
        Page<HfEnvTestVO> pageData = testService.pageVO(page, queryWrapper);
        /*计算分页信息返回给前端*/
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }


    @PostMapping("/startTest")
    @ApiOperation("试验开始")
    public BusiResponse startTest(@RequestBody @Validated HfEnvTestStartVO testStartVO) {
        testService.start(testStartVO);
        return BusiResponse.OK();
    }


    @PostMapping("/finishTest")
    @ApiOperation("试验完成")
    public BusiResponse finishTest(@RequestBody @Validated HfEnvTestFinishVO testStartVO) {
        testService.finish(testStartVO);
        return BusiResponse.OK();
    }

    @PostMapping("/forceEndTest")
    @ApiOperation("试验中断")
    public BusiResponse forceEndTest(@RequestBody @Validated HfEnvTestForceEndVO testForceEndVO) {
        testService.forceEnd(testForceEndVO);
        return BusiResponse.OK();
    }

    @GetMapping("/queryForceEndById")
    @ApiOperation("查询终止详情")
    public BusiResponse queryForceEndById(@RequestParam("id") String id) {
        HfEnvTestForceEndVO testForceEndVO = testService.queryForceEndById(id);
        return BusiResponse.OK(testForceEndVO);
    }


    @PostMapping("/revokeTest")
    @ApiOperation("试验撤销")
    public BusiResponse revokeTest(@RequestBody @Validated HfEnvTestRevokeVO testRevokeVO) {
        testService.revoke(testRevokeVO);
        return BusiResponse.OK();
    }

    @GetMapping("/queryTestData")
    @ApiOperation("查询试验数据")
    public BusiResponse queryTestData(@RequestParam("id") String id) {
        HfEnvTestDataVO testDataVO = testService.queryTestData(id);
        return BusiResponse.OK(testDataVO);
    }

    @PostMapping("/saveTestData")
    @ApiOperation("保存试验数据")
    public BusiResponse saveTestData(@RequestBody @Validated HfEnvTestDataVO testData) {
        testService.saveTestData(testData);
        return BusiResponse.OK();
    }


    @PostMapping("/queryCurveData")
    @ApiOperation("查询试验曲线数据")
    public BusiResponse queryCurveData(@RequestBody @Validated QueryCurveDataVO queryCurveDataVO) {
        String id = queryCurveDataVO.getId();
        Date startTime = queryCurveDataVO.getStartTime();
        Date endTime = queryCurveDataVO.getEndTime();
        HfEnvTest envTest = testService.getById(id);
        Assert.notNull(envTest, "数据不存在!");
        String equipCode = envTest.getEquipCode();
        String equipId = envTest.getEquipId();
        if (startTime == null) {
            startTime = envTest.getRealStartTime();
        }
        if (endTime == null) {
            endTime = new Date();
        }
        List<ClimateCollectionData> listData = collectDataService.listData(equipCode, startTime, endTime);
        return BusiResponse.OK(listData);
    }


    @ApiOperation("生成原始记录")
    @PostMapping("/generateProcessRecord")
    public BusiResponse generateProcessRecord(@RequestBody @Validated IdVO idVO) {
        testService.generateProcessRecord(idVO.getId());
        return BusiResponse.OK();
    }


    @ApiOperation("替换试验原始记录")
    @PostMapping("/replaceTestReport")
    public BusiResponse replaceTestReport(@RequestBody @Validated UploadFileVO uploadFileVO) {
        testService.replaceTestReport(uploadFileVO.getId(), uploadFileVO.getFileId());
        return BusiResponse.OK();
    }


    @ApiOperation("删除试验原始记录")
    @PostMapping("/delTestReport")
    public BusiResponse delTestReport(@RequestBody @Validated IdVO idVO) {
        testService.delTestReport(idVO.getId());
        return BusiResponse.OK();
    }


    @ApiOperation("试验总览")
    @PostMapping("/listPageAll")
    public BusiResponse listPageAll(@RequestBody TestQueryParamVO queryParamsVO) {
        QueryParamBean<HfEnvTestVO> queryParamBean = new QueryParamBean<>(queryParamsVO);
        queryParamBean.addColumns(HfEnvTest.class, "t");
        queryParamBean.addField("entrustCode", "ge");
        QueryWrapper<HfEnvTestVO> queryWrapper = queryParamBean.getQueryWrapper();
        Page<HfEnvTestVO> page = queryParamBean.getPage();
        queryWrapper.in("t.secret_level", SystemLoginUser.dataSecretSet);
        String finishFlag = queryParamsVO.getFinishFlag();
        String forceEndFlag = queryParamsVO.getForceEndFlag();
        if (Objects.equals(SystemConsts.NO, finishFlag)) {
            queryWrapper.ne("t.status", TestConsts.TEST_STATUS_FINISH);
        }
        if (Objects.equals(SystemConsts.NO, forceEndFlag)) {
            queryWrapper.ne("t.status", TestConsts.TEST_STATUS_STOP);
        }
        Page<HfEnvTestVO> pageData = testService.pageVO(page, queryWrapper);
        /*计算分页信息返回给前端*/
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }


    @ApiOperation("获取试验任务样品数据")
    @PostMapping("/listPageTestPiece")
    public BusiResponse listPageTestPiece(@RequestBody @Validated TestPieceQueryParamVO queryParamsVO) {
        String testId = queryParamsVO.getTestId();

        QueryParamBean<HfEnvGkPiece> pieceQueryParamBean = new QueryParamBean<>(queryParamsVO);
        pieceQueryParamBean.addColumns(HfEnvGkPiece.class);
        Page<HfEnvGkPiece> page = pieceQueryParamBean.getPage();
        QueryWrapper<HfEnvGkPiece> queryWrapper = pieceQueryParamBean.getQueryWrapper();

        QueryWrapper<HfEnvTaskTestRelation> taskTestRelationQueryWrapper = new QueryWrapper<>();
        taskTestRelationQueryWrapper.lambda()
                .eq(HfEnvTaskTestRelation::getTestId, testId);
        List<HfEnvTaskTestRelation> taskTestRelationList = taskTestRelationService.list(taskTestRelationQueryWrapper);
        List<String> gkEntrustIdList = taskTestRelationList.stream()
                .map(HfEnvTaskTestRelation::getGkEntrustId)
                .collect(Collectors.toList());
        Assert.notEmpty(gkEntrustIdList, "委托信息不存在!");

        queryWrapper.lambda()
                .in(HfEnvGkPiece::getGkEntrustId, gkEntrustIdList);
        Page<HfEnvGkPiece> pageData = gkPieceService.page(page, queryWrapper);
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }


    @ApiOperation("保存规划曲线")
    @PostMapping("/saveCurve")
    public BusiResponse saveCurve(@RequestBody @Validated HfEnvSaveCurveVO saveCurveVO) {
        testService.saveCurve(saveCurveVO);
        return BusiResponse.OK();
    }

    @ApiOperation("查询试验传感器")
    @PostMapping("/listPageTestSensor")
    public BusiResponse listPageTestSensor(@RequestBody @Validated TestItemQueryParamVO testItemQueryParamVO) {
        String testId = testItemQueryParamVO.getTestId();

        QueryParamBean<HfEnvTestSensor> testSensorQueryParamBean = new QueryParamBean<>(testItemQueryParamVO);
        testSensorQueryParamBean.addColumns(HfEnvTestSensor.class);
        Page<HfEnvTestSensor> page = testSensorQueryParamBean.getPage();
        QueryWrapper<HfEnvTestSensor> queryWrapper = testSensorQueryParamBean.getQueryWrapper();
        queryWrapper.lambda()
                .eq(HfEnvTestSensor::getTestId, testId);
        Page<HfEnvTestSensor> pageData = testSensorService.page(page, queryWrapper);
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }


    @PostMapping("/exportExcel")
    @ApiOperation(value = "试验查询功能:导出数据")
    public Object exportExcel(@RequestBody QueryParamsVO queryParamsVO) {
        QueryParamBean<HfEnvTestVO> queryParamBean = new QueryParamBean<>(queryParamsVO);

        queryParamBean.addColumns(HfEnvTest.class, "t");
        queryParamBean.addField("entrustCode", "e");
        QueryWrapper<HfEnvTestVO> queryWrapper = queryParamBean.getQueryWrapper();
        queryWrapper.in("t.secret_level", SystemLoginUser.dataSecretSet);

        BusiResponse export = testService.exportExcel(queryWrapper);
        if (export.getCode() == com.hifar.fw.utils.bean.BusiConst.CODE_SUCCESS) {
            String secretLevelText = StringUtils.trimNull(export.getExt("secretLevelText"), "公开");
            String encode = null;
            try {
                encode = URLEncoder.encode(String.format("试验查询_%s.xlsx", secretLevelText), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
        return export;
    }


}
